import fs from 'fs';
import readline from 'readline';

let configPath = './config/config.js';
import chalk from 'chalk';
const warning = chalk.bold.hex('#FFA500');

let rl;
export let BotConfig;
function question(query) {
  return new Promise(resolve => {
    if (!rl) return;
    rl.question(query.trim(), resolve);
  });
}

export async function check() {
  if (fs.existsSync(configPath)) {
    BotConfig = (await import(`../config/config.js`)).config;
    global.cfg=BotConfig;
  } else {
    rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    let appID, token;
    console.log(
      warning('请按提示输入，生成配置文件config.js，输入错误【Ctrl+c】结束重来')
    );
    appID = await question('请输入appID：\n');
    if (!appID) {
      return await check();
    }
    token = await question('请输入token(机器人令牌)：\n');
    if (!token) {
      return await check();
    }
    let str = fs.readFileSync('./config/config_default.js', 'utf8');
    str = str.replace(/appID(.*)'',/g, `appID: '${appID}',`);
    str = str.replace(/token(.*)'',/g, `token: '${token}',`);

    fs.writeFileSync(configPath, str);
    console.log('生成配置文件成功\n其他配置请打开config/config.js修改');
    BotConfig = (await import(`../config/config.js`)).config;
    global.cfg=BotConfig;
  }
}
